<template>
  <div class="app-container">
    <el-card>
      <el-button type="text">操作</el-button>
      <div class="filter-btn">
        <el-button
          type="success"
          size="mini"
          icon="el-icon-plus"
          @click="add"
        >
          添加
        </el-button>
      </div>
    </el-card>
    <el-row :gutter="48" class="table-container">
      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <el-button type="text">笔记</el-button>
          </div>
          <el-card shadow="hover">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
            />
          </el-card>
          <el-card
            v-for="(item,index) in noteList"
            :key="index"
            shadow="hover"
            class="first-row"
          >
            <el-row :gutter="24">
              <el-col
                :span="20"
              >
                <div
                  @click="selectNote(item)"
                >

                  <p class="name">{{ item.name }}</p>
                  <p class="abstract">{{ item.abstractContent }}</p>
                  <p class="time">{{ item.createTime | parseTime('{y}-{m}-{d}') }}</p>

                </div>
              </el-col>
              <el-col :span="4">
                <el-button size="small" type="danger" icon="el-icon-delete" @click.stop="remove(item, index)">删除</el-button>
              </el-col>
            </el-row>
          </el-card>

          <empty v-if="noteList.length === 0" />
        </el-card>

      </el-col>

      <el-col :sm="24" :lg="12">
        <el-card>
          <div slot="header" class="clearfix">
            <el-tag
              v-for="(tag,index) in note.tags"
              :key="index"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.name }}
            </el-tag>
            <el-input
              v-if="addTagVisible"
              ref="saveTagInput"
              v-model="newTagValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleNewTagConfirm"
              @blur="handleNewTagConfirm"
            />
            <el-button v-else type="info" class="button-new-tag" size="small" @click="showNewTag">+ 标签</el-button>
          </div>
          <el-form>
            <el-form-item label="标题：" prop="name">
              <el-input v-model="note.name" placeholder="标题" />
            </el-form-item>
            <el-form-item label="日记内容：" prop="content">
              <tinymce ref="content" v-model="note.content" width="100%" :height="400" />
            </el-form-item>
          </el-form>
          <span class="dialog-footer">
            <el-button type="primary" @click="handleSaveNote">保 存</el-button>
          </span>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {
  getList,
  create,
  updateById,
  getById,
  removeById
} from '@/api/life/note'

import {
  create as createTag,
  removeById as removeTag

} from '@/api/life/note-tag'

import Tinymce from '@/components/Tinymce'

import Empty from '@/components/Empty'

export default {
  name: 'Note',
  components: {
    Tinymce,
    Empty
  },
  data() {
    return {
      noteList: [],
      note: {},
      filterText: '',
      listQuery: {},

      newTagValue: '',

      addTagVisible: false
    }
  },
  watch: {
    filterText: function(newValue) {
      if (newValue) {
        this.listQuery.content = newValue
        this.listQuery.name = newValue

        this.getList()
      } else {
        this.listQuery.content = null
        this.listQuery.name = null
      }
    }
  },
  created() {
    const { noteBookId } = this.$route.query

    if (!noteBookId) {
      this.$router.push({
        path: '/life/days/note-book'
      })
    }

    this.noteBookId = noteBookId
    this.getList()
  },
  methods: {
    getList() {
      getList(this.listQuery).then(res => {
        this.noteList = res.data
      })
    },
    add() {
      this.handleSaveNote()
      this.emptyContent()
    },
    emptyContent() {
      this.note = {}
      this.$refs.content.setContent('')
    },
    handleSaveNote() {
      return new Promise(resolve => {
        const { id, content, name } = this.note

        if (!content && !name) {
          return
        }

        const param = Object.assign({}, this.note)
        param.noteBookId = this.noteBookId
        if (!id) {
          create(param).then(res => {
            resolve(res)
          })
        } else {
          updateById(id, param).then(_ => {
            resolve()
          })
        }
      })
    },
    handleClose(tag) {
      removeTag(tag.id)
    },
    showNewTag() {
      this.addTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleNewTagConfirm() {
      const note = this.note

      // 没有关联的笔记，直接创建一个空的note
      if (!note.id) {
        this.handleSaveNote().then(res => {
          this.note = res.data
        })
      }

      // 设置新的标签
      if (this.newTagValue) {
        if (!this.note.tags) {
          this.note.tags = []
        }

        createTag({
          noteId: this.note.id,
          name: this.newTagValue
        }).then(res => {
          this.note.tags.push({
            id: res.data.id,
            name: this.newTagValue
          })
        })
      }

      this.addTagVisible = false
      this.newTagValue = ''
    },
    selectNote(note) {
      // 选中之前，先保存当前编辑的笔记信息
      if (this.note.id !== note.id) {
        this.handleSaveNote()

        getById(note.id).then(res => {
          this.note = res.data

          this.$refs.content.setContent(res.data.content)
        })
      }
    },
    remove(note, index) {
      this.$confirm('是否要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeById(note.id).then(_ => {
          this.noteList.splice(index, 1)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.name{
  color: #000;
}

.abstract{
  color: #808080;
}

.time{
  color:#409EFF
}

.filter-container{
  margin-top:0px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.first-row{
  margin-top:20px;
}
.filter-btn{
  float: right;
}

</style>
